package com.aeks.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aeks.divide.FileDivide;
import com.aeks.divide.GenerateDictionary;
import com.aeks.divide.Segmentation;
import com.aeks.finalkey.InsertData;
import com.aeks.user.AboutUser;
import com.aeks.user.User;


public class GetReadyKeyServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		String fileID = (String)request.getParameter("fileid");
		String saveName = (String)request.getParameter("savename");
		String servletPath = this.getServletContext().getRealPath("/");// 获得服务器所在地址
		
		boolean isSuccess = true;
		String action = request.getParameter("action");
		if (action != null && action.equals("sedivide")) {
			HttpSession session = request.getSession();
			String username = (String)session.getAttribute("username");
			
			
			
			String dictname = "dic.txt";
			dictname = servletPath + "material\\" + dictname;
			HashMap hm = new HashMap();
			HashMap len = new HashMap();
			GenerateDictionary genDic = new GenerateDictionary();
			Segmentation seg = new Segmentation(hm, len);//分割，获得词及词的长度的hashmap
			genDic.GenHashDic(dictname, hm, len);
			
			List<String> slist = new ArrayList<String>();//装使用到的停用词的链表
			List<String> tlist = new ArrayList<String>();//title
			List<String> blist = new ArrayList<String>();//brief
			List<String> klist = new ArrayList<String>();//key
			List<String> ttlist = new ArrayList<String>();//title
			
			String path = servletPath + "tempFile";
			String titleFile = path + "\\" + saveName + "titlePart.txt";
			File tf = new File(titleFile);
			if(tf.exists()) {
				String FmmTarget = "";
				FileReader tfr = new FileReader(tf);
				BufferedReader tbr = new BufferedReader(tfr);
				String s = tbr.readLine();
				while(s!= null) {
					s = s.replaceAll(" ", "").trim();
					FmmTarget = seg.Fmm(s);
					//System.out.println("title:" + FmmTarget);
					
					String[] result = FmmTarget.split("/");
					List<String> l = FileDivide.deleteStop(result, slist, servletPath);
					tlist.addAll(l);
					s = tbr.readLine();
				}
				//System.out.println(tlist.size());
				if(tlist == null || tlist.size() < 1) {
					isSuccess = false;
				}
				tbr.close();
				tfr.close();
			} else {
				isSuccess = false;
			}
			
			if(isSuccess) {
				String briefFile = path + "\\" + saveName + "briefPart.txt";
				File bf = new File(briefFile);
				if(bf.exists()) {
					String FmmTarget = "";
					FileReader bfr = new FileReader(bf);
					BufferedReader bbr = new BufferedReader(bfr);
					String s = bbr.readLine();
					while(s!= null) {
						s = s.replaceAll(" ", "").trim();
						FmmTarget = seg.Fmm(s);
						//System.out.println("brief:" + FmmTarget);
						
						String[] result = FmmTarget.split("/");
						List<String> l = FileDivide.deleteStop(result, slist, servletPath);
						blist.addAll(l);
						s = bbr.readLine();
					}
					//System.out.println(blist.size());
					if(blist == null || blist.size() < 1) {
						isSuccess = false;
					}
					bbr.close();
					bfr.close();
				} else {
					isSuccess = false;
				}
			}
			
			if(isSuccess) {
				String keyFile = path + "\\" + saveName + "keyPart.txt";
				File kf = new File(keyFile);
				if(kf.exists()) {
					String FmmTarget = "";
					FileReader kfr = new FileReader(kf);
					BufferedReader kbr = new BufferedReader(kfr);
					String s = kbr.readLine();
					while(s!= null) {
						s = s.replaceAll(" ", "").trim();
						FmmTarget = seg.Fmm(s);
						//System.out.println("key:" + FmmTarget);
						
						String[] result = FmmTarget.split("/");
						List<String> l = FileDivide.deleteStop(result, slist, servletPath);
						klist.addAll(l);
						s = kbr.readLine();
					}
					//System.out.println(klist.size());
					if(klist == null || klist.size() < 1) {
						isSuccess = false;
					}
					kbr.close();
					kfr.close();
				} else {
					isSuccess = false;
				}
			}
			
			if(isSuccess) {
				String textFile = path + "\\" + saveName + "textPart.txt";
				File ttf = new File(textFile);
				if(ttf.exists()) {
					String FmmTarget = "";
					FileReader ttfr = new FileReader(ttf);
					BufferedReader ttbr = new BufferedReader(ttfr);
					String s = ttbr.readLine();
					while(s!= null) {
						s = s.replaceAll(" ", "").trim();
						FmmTarget = seg.Fmm(s);
						//System.out.println("text:" + FmmTarget);
						
						String[] result = FmmTarget.split("/");
						List<String> l = FileDivide.deleteStop(result, slist, servletPath);
						ttlist.addAll(l);
						s = ttbr.readLine();
					}
					//System.out.println(ttlist.size());
					if(ttlist == null || ttlist.size() < 1) {
						isSuccess = false;
					}
					ttbr.close();
					ttfr.close();
				} else {
					isSuccess = false;
				}
			}
			
			//System.out.println(tlist.size());
			//System.out.println(blist.size());
			//System.out.println(klist.size());
			//System.out.println(ttlist.size());
			
			//System.out.println(isSuccess);
			//System.out.println(slist.size());
			if(isSuccess && slist != null && slist.size() > 0) {
				if(!FileDivide.inputStopFile(slist, path, saveName)) {
					isSuccess = false;
				}
			} else {
				isSuccess = false;
			}
			
			
			
			if(isSuccess) {
				List<User> ulist = AboutUser.getUser(username);
				User u = null;
				if(ulist != null && ulist.size()>0) {
					u = ulist.get(0);
				} else {
					isSuccess = false;
				}
				if(isSuccess && countFrequency(tlist, blist, klist, ttlist, u, fileID)){
					isSuccess = true;
				} else {
					isSuccess = false;
				}
			}
			
		} else {//if(action)
			isSuccess = false;
		}
		
		if(isSuccess) {
			out.println("<script language='javascript'>");
			out.println("alert('处理文献成功！');");
			//System.out.println(fileID);
			//System.out.println(servletPath);
			out.println("window.location.href='main.jsp?action=dealSuccess&fileID=" + fileID + "'");
			out.println("</script>");
		} else {
			out.println("<script language='javascript'>");
			out.println("alert('不能获取正确处理该文献！');");
			out.println("window.location.href='main.jsp'");
			out.println("</script>");
		}
		out.flush();
		out.close();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	private boolean countFrequency(List<String> tlist, List<String> blist, List<String> klist, List<String> ttlist, User u, String fileID) {
		int count = tlist.size() + blist.size() + klist.size() + ttlist.size();
		List<String> alist = new ArrayList<String>();//所有链表中的元素放在一个大的链表中
		alist.addAll(tlist);
		alist.addAll(blist);
		alist.addAll(klist);
		alist.addAll(ttlist);
		
		Map<String, Integer> map = new HashMap<String, Integer>();//装计算了的备选关键字的值
		List<Map> amlist = new ArrayList<Map>();
		float lvalue = u.getLimitValue();
		getCount(tlist, alist, amlist, map, u.getTitleValue(), lvalue);
		getCount(blist, alist, amlist, map, u.getBriefValue(), lvalue);
		getCount(klist, alist, amlist, map, u.getKeyValue(), lvalue);
		getCount(ttlist, alist, amlist, map, u.getTextValue(), lvalue);
		
		if(InsertData.insertFinalKey(amlist, fileID)) {
			return true;
		} else {
			return false;
		}
		
	}
	
	private boolean getCount(List<String> list, List<String> alist, List<Map> mlist, Map<String, Integer> map, float value, float lvalue) {
		for(int i=0; i<list.size(); i++) {
			String s = list.get(i);
			
			if(!map.containsKey(s)) {//该关键字没有计算过
				//System.out.println(s);
				map.put(s, s.length());
				int n = 0;
				for(int j=0; j<alist.size(); j++) {
					String as = alist.get(j);
					if(s.equals(as)) {
						n ++;
					}
				}
				
				double freq = (n * 1.0) / alist.size(); 
				double cvalue = freq * value;
				String isKey = "0";
				if(cvalue >= lvalue) {
					isKey = "1";
				} else {
					isKey = "0";
				}
				
				Map<Object, Object> map2 = new HashMap<Object, Object>();
				map2.put("keyvalue", s);
				map2.put("length", s.length());
				map2.put("freq", freq);
				map2.put("cvalue", cvalue);
				map2.put("iskey", isKey);
				mlist.add(map2);
			}
		}
		return false;
	}

}
